package o2o.web.actions.sys;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ObjectUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.sys.SysConfigJPushCache;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.sys.JPUSH_TYPE;
import o2o.dao.PO.sys.SysConfigJPush;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.common.FileStoryInfo;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.dao.VO.sys.SysConfigJPushSubVO;
import o2o.dao.VO.sys.SysConfigJPushVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.utils.FileUtils;
import o2o.web.actions.user.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class SysConfigJPushAction {

    //获取所有极光推送的配置
    @RequestMapping(method = RequestMethod.POST, value = "/admin/sys/config/jpush/list")
    @ResponseBody
    public String getJPushSysConfigs(String token) {
        //登录验证
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //权限验证
        if (!User.getInstance().hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有访问权限");
        }
        List<SysConfigJPush> list = SysConfigJPushCache.getInstance().getAllJPushList();
        List<SysConfigJPushVO> sysConfigJPushVOs = new ArrayList<>();
        SysConfigJPushVO sysConfigJPushVO = null;
        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                sysConfigJPushVO = new SysConfigJPushVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), sysConfigJPushVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                sysConfigJPushVOs.add(sysConfigJPushVO);
            }
        }
        return AjaxResult.successResult(sysConfigJPushVOs.size(), sysConfigJPushVOs);
    }

    //根据端获取推送信息
    @RequestMapping(method = RequestMethod.POST, value = "/sys/config/jpush/get")
    @ResponseBody
    public String getJPushSysConfigs(String token, String sysAppKey, Integer code, Integer type) {
        if (ValidateUtil.isNotAbsInteger(code)) {
            return AjaxResult.errorResult("请选择要查看的编号");
        }
        // add  by yangtk 2019年4月16日14:53:51
        if (type == null || (
                type != JPUSH_TYPE.TYPE_NEW_ORDER
                        && type != JPUSH_TYPE.TYPE_CANCEL_ORDER
                        && type != JPUSH_TYPE.TYPE_AUTO_ACCEPT_ORDER
                        && type != JPUSH_TYPE.TYPE_REMINDER
                        && type != JPUSH_TYPE.TYPE_DISPATCH
        )) {
            type = JPUSH_TYPE.TYPE_NEW_ORDER;
        }

//        SysConfigJPush sysConfigJPush = SysConfigJPushCache.getInstance().getByCode(code);
        SysConfigJPush sysConfigJPush = SysConfigJPushCache.getInstance().getByCode(code, type);

        if (null == sysConfigJPush) {
            return AjaxResult.errorResult("不存在，请联系管理员");
        }
        SysConfigJPushSubVO sysConfigJPushVO = new SysConfigJPushSubVO();
        try {
            ObjectUtils.copyPropertiesExclude(sysConfigJPush, sysConfigJPushVO);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败，请稍后再试");
        }

        return AjaxResult.successResult(sysConfigJPushVO);
    }

    //根据端获取推送信息
    @RequestMapping(method = RequestMethod.POST, value = "/sys/config/jpush/list")
    @ResponseBody
    public String listJPushSysConfigs(String token, String sysAppKey, Integer code) {
        // code
        List<SysConfigJPush> list = null;
        if (code == null) {
            list = SysConfigJPushCache.getInstance().getAllJPushList();
        } else {
            list = SysConfigJPushCache.getInstance().getJPushListByCode(code);
        }
        if (ValidateUtil.isAbsList(list)) {
            List<SysConfigJPushVO> reList = new ArrayList<>();
            for (SysConfigJPush jPush : list) {
                SysConfigJPushVO vo = new SysConfigJPushVO();
                BeanUtils.copyProperties(jPush, vo);
                reList.add(vo);
            }
            return AjaxResult.successResult(list.size(), list);
        }
        return AjaxResult.successResult(0, null);
    }

    //单个推荐配置更新
    @RequestMapping(method = RequestMethod.POST, value = "/admin/sys/config/jpush/update")
    @ResponseBody
    public String updateJpushConfig(String token, Integer code, String app_key, String master_secret, String sound, String projectName, String note, Integer type, FileUploadInfo fileUploadInfo) throws Exception {
        boolean isUpdateData = false; //判断数据是否更新
        // 登录验证
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //权限验证
        if (!User.getInstance().hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有访问权限");
        }
        //code验证
        if (!ValidateUtil.isAbsInteger(code)) {
            return AjaxResult.errorResult("code不能为空，请重试");
        }
        // add by yangtk  2019年4月16日14:55:04
        if (type == null || (
                type != JPUSH_TYPE.TYPE_NEW_ORDER
                        && type != JPUSH_TYPE.TYPE_CANCEL_ORDER
                        && type != JPUSH_TYPE.TYPE_AUTO_ACCEPT_ORDER
                        && type != JPUSH_TYPE.TYPE_REMINDER
                        && type != JPUSH_TYPE.TYPE_DISPATCH
        )) {
            type = JPUSH_TYPE.TYPE_NEW_ORDER;
        }
        // end
//        SysConfigJPush getByCode = SysConfigJPushCache.getInstance().getByCode(code);
        SysConfigJPush getByCode = SysConfigJPushCache.getInstance().getByCode(code, type);
        //理论此情况不存在在
        if (null == getByCode) {
            return AjaxResult.errorResult("该配置信息不存在~");
        }
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.SYS_CONFIG_JPUSH).append(" set ");
        if (ValidateUtil.isNotNull(app_key) && !app_key.equals(getByCode.getApp_key())) {
            isUpdateData = true;
            sb.append(" app_key = '").append(app_key).append("',");
        }
        if (ValidateUtil.isNotNull(sound) && !sound.equals(getByCode.getSound())) {
            isUpdateData = true;
            sb.append(" sound = '").append(sound).append("',");
        }
        if (ValidateUtil.isNotNull(projectName) && !projectName.equals(getByCode.getProjectName())) {
            isUpdateData = true;
            sb.append(" projectName = '").append(projectName).append("',");
        }
        if (ValidateUtil.isNotNull(master_secret) && !master_secret.equals(getByCode.getMaster_secret())) {
            isUpdateData = true;
            sb.append(" master_secret =  '").append(master_secret).append("' ,");
        }
        if (ValidateUtil.isNotNull(note) && !note.equals(getByCode.getNote())) {
            isUpdateData = true;
            sb.append(" note =  '").append(note).append("' ,");
        }

        String filePath = null;
        if (null != fileUploadInfo) {
            FileStoryInfo fileStoryInfo = FileUtils.saveVideo2Local(fileUploadInfo.getFile(), SYS_CONFIG_PATH.IMAGE_BASE_FILE, SYS_CONFIG_PATH.IMAGE_BASE_URL, SYS_CONFIG_PATH.NOTICE_IMAGE);
            if (ValidateUtil.isNull(fileStoryInfo.getUrl())) {
                return AjaxResult.errorResult("存储文件失败，请稍后再试");
            }
            isUpdateData = true;
            sb.append(" soundUrl =  '").append(fileStoryInfo.getUrl()).append("' ,");
        }

        sb.append(" updateUser = '").append(user.getUsername()).append("', updateTime = '").append(simpleDateFormat.format(date)).append("' ");
//        sb.append(" where code = ").append(code);
        sb.append(" where code = ").append(code).append(" and type = ").append(type);
        if (!isUpdateData) {
            return AjaxResult.errorResult("您没有更新任何信息");
        } else {
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("更新失败，请稍后再试.");
            }
        }
        SysConfigJPushCache.getInstance().run();
        return AjaxResult.successResult();
    }

    //  添加配置
    @RequestMapping(method = RequestMethod.POST, value = "/admin/sys/config/jpush/add")
    @ResponseBody
    public String addJpushConfig(String token, SysConfigJPush info, FileUploadInfo fileUploadInfo) throws Exception {
        // 登录验证
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //权限验证
        if (!User.getInstance().hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有访问权限");
        }
        //code验证
        if (!ValidateUtil.isAbsInteger(info.getCode())) {
            return AjaxResult.errorResult("code不能为空，请重试");
        }

        // add by yangtk  2019年4月16日14:55:04
        if (info.getType() == null || (
                info.getType() != JPUSH_TYPE.TYPE_NEW_ORDER
                        && info.getType() != JPUSH_TYPE.TYPE_CANCEL_ORDER
                        && info.getType() != JPUSH_TYPE.TYPE_AUTO_ACCEPT_ORDER
                        && info.getType() != JPUSH_TYPE.TYPE_REMINDER
        )) {
            info.setType(JPUSH_TYPE.TYPE_NEW_ORDER);
        }
        SysConfigJPush getByCode = SysConfigJPushCache.getInstance().getByCode(info.getCode(), info.getType());
        //理论此情况不存在在
        if (null != getByCode) {
            return AjaxResult.errorResult("该配置信息已存在~");
        }
        String filePath = null;
        if (null != fileUploadInfo) {
            FileStoryInfo fileStoryInfo = FileUtils.saveVideo2Local(fileUploadInfo.getFile(), SYS_CONFIG_PATH.IMAGE_BASE_FILE, SYS_CONFIG_PATH.IMAGE_BASE_URL, SYS_CONFIG_PATH.NOTICE_IMAGE);
            if (ValidateUtil.isNull(fileStoryInfo.getUrl())) {
                return AjaxResult.errorResult("存储文件失败，请稍后再试");
            }
            info.setSoundUrl(filePath);
        }
        Long cTime = DateUtils.getCurrTime();
        info.setCreateTime(cTime);
        info.setCreateUser(user.getUsername());
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.SYS_CONFIG_JPUSH, info);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("保存失败,请稍后重试");
        }
        SysConfigJPushCache.getInstance().run();
        return AjaxResult.successResult();
    }

    //获取所有极光推送的配置
    @RequestMapping(method = RequestMethod.POST, value = "/admin/sys/config/jpush/code/list")
    @ResponseBody
    public String getJPushSysConfigs_by_code(String token, Integer code) {
        //登录验证
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //权限验证
        if (!User.getInstance().hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有访问权限");
        }
        List<SysConfigJPush> list = SysConfigJPushCache.getInstance().getJPushListByCode(code);
        List<SysConfigJPushVO> sysConfigJPushVOs = new ArrayList<>();
        SysConfigJPushVO sysConfigJPushVO = null;
        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                sysConfigJPushVO = new SysConfigJPushVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), sysConfigJPushVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                sysConfigJPushVOs.add(sysConfigJPushVO);
            }
        }
        return AjaxResult.successResult(sysConfigJPushVOs.size(), sysConfigJPushVOs);
    }

}
